package com.haven123.cloudapp.redis.script;

import com.haven123.cloudapp.redis.api.EdenRedisScript;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.Collections;

/**
 * @author haven
 */
@Component("edenRedisScript")
public class EdenRedisScriptImpl implements EdenRedisScript, InitializingBean {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Boolean setIfAbsent(String key) {
        return setIfAbsent(key, 60);
    }

    @Override
    public Boolean setIfAbsent(String key, long expireTime) {
        return redisTemplate.execute(setIfAbsent, Collections.singletonList(key), expireTime);
    }

    private DefaultRedisScript<Boolean> setIfAbsent;

    @Override
    public void afterPropertiesSet() throws Exception {
        setIfAbsent = new DefaultRedisScript<>();
        setIfAbsent.setResultType(Boolean.class);
        setIfAbsent.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis/script/setIfAbsent.lua")));
    }
}
